<template>
  <el-dialog :title="'修改密码'" :visible.sync="dialogVisible" width="40%" :close-on-click-modal="false" append-to-body>
    <el-form ref="dataForm" :rules="modelRules" :model="model" label-width="130px">
      <el-form-item :label="'原密码'" prop="password">
        <el-input :key="isPasswordType" v-model="model.password" :placeholder="'旧密码'" @keyup.native="checkCapslock" @blur="capsTooltip = false">
        </el-input>
      </el-form-item>
      <el-tooltip v-model="capsTooltip" :content="'大写锁定已开启'" placement="top" manual>
        <el-form-item :label="'新密码'" prop="new_password">
          <el-input :key="isPasswordType" v-model="model.new_password" :type="isPasswordType?'new_password':''" :placeholder="'新密码'" @keyup.native="checkCapslock" @blur="capsTooltip = false">
            <template slot="append">
              <span class="show-pwd" @click="isPasswordType = !isPasswordType">
                <svg-icon :icon-class="isPasswordType ? 'eye' : 'eye-open'" />
              </span>
            </template>
          </el-input>
        </el-form-item>
      </el-tooltip>
      <el-form-item :label="'确认密码'" prop="confirmPassword">
        <el-input :key="isPasswordType" v-model="model.confirmPassword" :type="isPasswordType?'new_password':''" :placeholder="'确认密码'" @keyup.native="checkCapslock" @blur="capsTooltip = false">
          <template slot="append">
            <span class="show-pwd" @click="isPasswordType = !isPasswordType">
              <svg-icon :icon-class="isPasswordType ? 'eye' : 'eye-open'" />
            </span>
          </template>
        </el-input>
      </el-form-item>
    </el-form>
    <div slot="footer" class="dialog-footer">
      <el-button @click="close()">取消</el-button>
      <el-button type="primary" :loading="isSubmitLoading" @click="save()">提交</el-button>
    </div>
  </el-dialog>
</template>
<script>
import { changeMyPassword, getPasswordComplexitySetting } from "@/api/identity/user";

export default {
  data() {
    const validatePassword = (rule, value, callback) => {
      const givenPassword = value;
      if (!givenPassword || givenPassword.length < 0) {
        callback(new Error(this.$t("login.passwordEmptyError")));
      }

      // const requiredLength = this.passwordComplexitySetting.requiredLength;
      const requiredLength = 6;
      if (
        requiredLength &&
        givenPassword &&
        givenPassword.length < requiredLength
      ) {
        callback(
          new Error(
            '密码长度不能少于6位'
            // `${this.$t("users.minPassword")}${requiredLength}${this.$t(
            //   "users.chartPassword"
            // )}`
          )
        );
      }

      // const requireDigit = this.passwordComplexitySetting.requireDigit;
      // if (requireDigit && givenPassword && !/[0-9]/.test(givenPassword)) {
      //   callback(new Error(this.$t("users.requireDigit")));
      // }

      // const requireUppercase = this.passwordComplexitySetting.requireUppercase;
      // if (requireUppercase && givenPassword && !/[A-Z]/.test(givenPassword)) {
      //   callback(new Error(this.$t("users.requireUppercase")));
      // }

      // const requireLowercase = this.passwordComplexitySetting.requireLowercase;
      // if (requireLowercase && givenPassword && !/[a-z]/.test(givenPassword)) {
      //   callback(new Error(this.$t("users.requireLowercase")));
      // }

      // const requireNonAlphanumeric = this.passwordComplexitySetting
      //   .requireNonAlphanumeric;
      // if (
      //   requireNonAlphanumeric &&
      //   givenPassword &&
      //   /^[0-9a-zA-Z]+$/.test(givenPassword)
      // ) {
      //   callback(new Error(this.$t("users.requireNonAlphanumeric")));
      // }

      callback();
    };

    const validateConfirmPassword = (rule, value, callback) => {
      const givenPassword = value;

      if (givenPassword !== this.model.new_password) {
        callback(new Error('新密码与确认密码不一致'));
        // callback(new Error(this.$t("users.samePassword")));
      }

      callback();
    };
    return {
      passwordComplexitySetting: {},
      dialogVisible: false,
      isSubmitLoading: false,
      model: {
        password: "",
        new_password: "",
        confirmPassword: ""
      },
      modelRules: {
        password: [{ required: true, trigger: "blur", validator: validatePassword }],
        new_password: [
          {
            required: true,
            trigger: "blur",
            validator: validatePassword
          }
        ],
        confirmPassword: [
          {
            required: true,
            trigger: "blur",
            validator: validateConfirmPassword
          }
        ]
      },
      isPasswordType: true,
      capsTooltip: false
    };
  },
  methods: {
    show(id) {
      this.resetModal();
      this.model.id = id;
      // getPasswordComplexitySetting().then(result => {
      //   this.passwordComplexitySetting = result;

      this.dialogVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
      // });
    },
    resetModal() {
      this.model = {
        password: "",
        new_password: "",
        confirmPassword: ""
      };
    },
    save() {
      this.isSubmitLoading = true;
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          changeMyPassword(this.model)
            .then(() => {
              this.$message({
                message: this.$t("editSuccess"),
                type: "success"
              });
              this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
              this.close();
            })
            .catch(() => {
              this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
            });
        } else {
          this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
          this.$message({
            message: this.$t("formIsNotValidMessage"),
            type: "warning"
          });
        }
      });
    },
    close() {
      this.dialogVisible = false;
      this.isSubmitLoading = false; // 无论成功失败，都把按钮的loading状态取消
    },
    checkCapslock({ shiftKey, key } = {}) {
      if (key && key.length === 1) {
        if (
          (shiftKey && (key >= "a" && key <= "z")) ||
          (!shiftKey && (key >= "A" && key <= "Z"))
        ) {
          this.capsTooltip = true;
        } else {
          this.capsTooltip = false;
        }
      }
      if (key === "CapsLock" && this.capsTooltip === true) {
        this.capsTooltip = false;
      }
    }
  }
};
</script>
